package com.ksyun.campus.dataserver.services;

import cn.hutool.core.net.NetUtil;
import com.ksyun.campus.common.constant.ZkConstant;
import com.ksyun.campus.common.domain.DataServer;
import com.ksyun.campus.common.util.ByteConvertUtil;
import com.ksyun.campus.dataserver.bootstrap.DataServerInstance;
import com.ksyun.campus.dataserver.bootstrap.Root;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class RegistService implements ApplicationRunner{
    private String ipAddress = NetUtil.getLocalhostStr();

    @Autowired
    private CuratorFramework curatorFramework;

    @Value("${server.port}")
    private int port;

    @Value("${spring.application.name}")
    private String serviceName;

    @Autowired
    private Root root;

    /**
     * 初始容量 b 为单位
     */
    private int capacity = 1073741824;

    @Value("${az.rack}")
    private String rack;

    @Value("${az.zone}")
    private String zone;

    private String path;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("数据服务注册~");
        DataServerInstance.init(ipAddress, port, capacity, rack, zone);
        this.path = String.format("%s/%s/%s:%s", ZkConstant.ROOT_PATH, serviceName, ipAddress, port);
        registToCenter();
        root.initPath();
    }

    private void registToCenter() {
        // todo 将本实例信息注册至zk中心，包含信息 ip、port、capacity、rack、zone
        log.info("注册服务~");
        try {
            if (curatorFramework.checkExists().forPath(path) == null) {
                DataServer dataServer = DataServerInstance.getDataServer();
                curatorFramework.create()
                        .creatingParentsIfNeeded()
                        .withMode(CreateMode.EPHEMERAL)
                        .forPath(path, ByteConvertUtil.toByte(dataServer));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Map<String, Integer>> getDslist() {
        return null;
    }


    /**
     * 服务注销
     */
    @PreDestroy
    public void unregister(){
        log.info("服务注销~");
        try {
            curatorFramework.delete().forPath(this.path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 定时上报信息
     */
    @Scheduled(initialDelay = 20000, fixedDelay = 10000)
    public void reportToCenter(){
        try {
//            log.info("更新数据服务信息~");
            DataServer dataServer = DataServerInstance.getDataServer();
            curatorFramework.setData()
                    .forPath(path, ByteConvertUtil.toByte(dataServer));
        } catch (Exception e) {
            registToCenter();
        }
    }


}
